import React, { useRef, useState, useEffect } from "react";
import { Card, message, Button, Upload, Form, Image, Modal, Input } from "antd";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { EditableProTable, BetaSchemaForm } from "@ant-design/pro-components";
import request from "@/utils/request";
import { PlusOutlined } from "@ant-design/icons";
import type { UploadFile } from "antd/es/upload/interface";
import ProductForm from "./components/ProductForm";
import { api } from "@/utils/env";

interface ProductItem {
  id: string;
  name: string;
  purchasePrice: number;
  marketPrice: number;
  batchNo: string;
  notice?: string;
  categoryId: string;
  brandId: string;
  sort: number;
  status: boolean;
  mainImage: string;
  categoryName: string;
  brandName: string;
  images: string[];
  priceHistory?: {
    date: string;
    marketPrice: number;
    purchasePrice: number;
  }[];
}

const ProductList: React.FC = () => {
  const [editableKeys, setEditableKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<ProductItem[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ProductItem>();
  const [selectedCategory, setSelectedCategory] = useState<string>();
  const [selectedBrand, setSelectedBrand] = useState<string>();
  const [brandOptions, setBrandOptions] = useState<{ label: string; value: string }[]>([]);
  const [queryParams, setQueryParams] = useState({
    categoryId: undefined,
    brandId: undefined,
    current: 1,
  });
  const [verificationModalVisible, setVerificationModalVisible] = useState(false);
  const [verificationRecord, setVerificationRecord] = useState<ProductItem | null>(null);
  const [verificationAnswer, setVerificationAnswer] = useState<string>('');
  const [verificationQuestion, setVerificationQuestion] = useState<{num1: number; num2: number}>({ num1: 0, num2: 0 });

  const columns: ProColumns<ProductItem>[] = [
    {
      title: "商品名称",
      dataIndex: "name",
      width: 200,

      search: {
        transform: (value) => ({ name: value }),
      },
    },
    {
      title: "商品主图",
      dataIndex: "mainImage",
      width: 100,
      valueType: "image",
      render: (dom, entity, index, action, schema) => (
        <Image width={30} src={`${api}${entity.mainImage}`} />
      ),
      search: false,
    },
    {
      title: "商品图片列表",
      dataIndex: "images",
      width: 200,
      render: (dom, entity, index, action, schema) => (
        <Image.PreviewGroup>
          {entity.images.map((item, index) => (
            <Image key={index} width={30} src={`${api}${item}`} />
          ))}
        </Image.PreviewGroup>
      ),
      search: false,
    },
    {
      title: "采购价格",
      dataIndex: "purchasePrice",
      width: 120,
      valueType: "money",

      search: {
        transform: (value) => ({ purchasePrice: value }),
      },
    },
    {
      title: "市场价格",
      dataIndex: "marketPrice",
      width: 120,
      valueType: "money",

      search: {
        transform: (value) => ({ marketPrice: value }),
      },
    },
    {
      title: "批次号",
      dataIndex: "batchNo",
      width: 120,

      search: {
        transform: (value) => ({ batchNo: value }),
      },
    },
    {
      title: "商品分类",
      dataIndex: "categoryId",
      width: 120,
      valueType: "select",
      render: (_, record) => record.categoryName,
      request: async () => {
        const res = await request.get("/categories/list");

        return res?.data?.list.map((item: any) => ({
          label: item.name,
          value: item.id,
        }));
      },
      search: {
        transform: (value) => ({ categoryId: value }),
      },
    },
    {
      title: "商品品牌",
      dataIndex: "brandId",
      width: 120,
      valueType: "select",
      render: (_, record) => record.brandName,
      dependencies: ["categoryId"],
      request: async (params) => {
        const categoryId = form.getFieldValue('categoryId');
        if (!categoryId) return [];
        const res = await request.get("/brands/list", {
          params: { categoryId }
        });
        return res.data?.list?.map((item: any) => ({
          label: item.name,
          value: item.id,
        }));
      },
      search: {
        transform: (value) => ({ brandId: value }),
      },
    },
    {
      title: "排序",
      dataIndex: "sort",
      width: 80,
      valueType: "digit",
      search: false,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 80,
      valueType: "switch",
      search: {
        transform: (value) => ({ status: value }),
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 200,
      search: false,
      fixed:'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            setCurrentRecord(record);
            setModalVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="copy"
          onClick={() => handleCopy(record)}
          style={{ margin: '0 8px' }}
        >
          复制
        </a>,
        <a
          key="delete"
          onClick={() => {
            setVerificationRecord(record);
            setVerificationModalVisible(true);
            generateQuestion();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const generateQuestion = () => {
    const num1 = Math.floor(Math.random() * 50);
    const num2 = Math.floor(Math.random() * 50);
    setVerificationQuestion({ num1, num2 });
    setVerificationAnswer('');
  };

  const handleVerification = async () => {
    const correctAnswer = verificationQuestion.num1 + verificationQuestion.num2;
    if (Number(verificationAnswer) === correctAnswer) {
      try {
        await request.post("/products/delete", {
          id: verificationRecord?.id,
        });
        message.success("删除成功");
        actionRef.current?.reload();
        setVerificationModalVisible(false);
        setVerificationRecord(null);
      } catch (error) {
        message.error("删除失败");
      }
    } else {
      message.error("计算错误，请重试");
      generateQuestion();
    }
  };

  const handleDelete = (record: ProductItem) => {
    setVerificationRecord(record);
    setVerificationModalVisible(true);
    generateQuestion();
  };





  const handleSubmit = async (values: ProductItem) => {
    try {
      if (currentRecord) {
        // 更新
        await request.post("/products/update", {
          ...values,
          id: currentRecord.id,
        });
        message.success("更新成功");
      } else {
        // 创建
        await request.post("/products/create", values);
        message.success("创建成功");
      }
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error(currentRecord ? "更新失败" : "创建失败");
    }
  };

  const handleCategoryChange = async (value: string) => {
    setSelectedCategory(value);
    setSelectedBrand(undefined);
    if (value) {
      try {
        const response = await getBrandsByCategory(value);
        if (response.success) {
          setBrandOptions(response.data.list.map((brand: any) => ({
            label: brand.name,
            value: brand.id
          })));
        }
      } catch (error) {
        message.error('获取品牌列表失败');
      }
    } else {
      setBrandOptions([]);
    }
    setQueryParams(prev => ({
      ...prev,
      categoryId: value,
      brandId: undefined,
      current: 1
    }));
  };

  const getBrandsByCategory = async (categoryId: string) => {
    return await request.get("/brands/list", {
      params: { categoryId }
    });
  };

  const handleCopy = async (record: ProductItem) => {
    try {
      const result = await request.post('/products/copy', { id: record.id });
      if (result?.success) {
        message.success('复制成功');
        // 刷新列表
        actionRef.current?.reload();
      } else {
        message.error('复制失败');
      }
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败');
    }
  };

  useEffect(() => {
    // const fetchInitialData = async () => {
    //   try {
    //     const categoryRes = await getCategories();
    //     if (categoryRes.success) {
    //       setCategoryOptions(categoryRes.data.list.map((category: any) => ({
    //         label: category.name,
    //         value: category.id
    //       })));
    //     }
    //   } catch (error) {
    //     message.error(error);
    //   }
    // };

    // fetchInitialData();
  }, []);

  return (
    <div>
      <Card className="search-card" style={{ marginBottom: 24 }}>
        <BetaSchemaForm
          form={form}
          layoutType="QueryFilter"
          columns={columns.filter((col) => col.search !== false)}
          onValuesChange={(changedValues) => {
            if (changedValues.categoryId !== undefined) {
              form.setFieldsValue({ brandId: undefined });
            }
          }}
          onFinish={async (values) => {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }}
        />
      </Card>

      <Card>
        <EditableProTable<ProductItem>
          rowKey="id"
          actionRef={actionRef}
          columns={columns}
          value={dataSource}
          onChange={setDataSource}
          recordCreatorProps={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="create"
              onClick={() => {
                setCurrentRecord(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          pagination={{
            pageSize: 10,
          }}
          request={async (params) => {
            const { current, pageSize, ...searchParams } = params;
            // 获取表单中的查询条件
            const formValues = form.getFieldsValue();
            
            const res = await request.post("/products/list", {
              current,
              pageSize,
              ...formValues,  // 使用表单值
              ...searchParams,  // 保留其他搜索参数
            });

            return {
              data: res?.data?.list || [],
              success: true,
              total: res?.data?.total || 0,
            };
          }}
          dateFormatter="string"
          headerTitle="商品列表"
        />
      </Card>

     <Modal
        title="删除验证"
        open={verificationModalVisible}
        onOk={handleVerification}
        maskClosable={false}
        onCancel={() => {
          setVerificationModalVisible(false);
          setVerificationRecord(null);
        }}
      >
        <p>为了防止误操作，请回答下面的问题：</p>
        <p>{verificationQuestion.num1} + {verificationQuestion.num2} = ?</p>
        <Input
          placeholder="请输入答案"
          value={verificationAnswer}
          onChange={(e) => setVerificationAnswer(e.target.value)}
          type="number"
        />
      </Modal>
      
      {modalVisible &&<Modal    maskClosable={false}
        title={currentRecord ? "编辑商品" : "新建商品"}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRecord(undefined);
        }}
        footer={null}
        width={800}
        destroyOnClose
      >
        <ProductForm initialValues={currentRecord}  />
      </Modal> } 
    </div>
  );
};

export default ProductList;
